package redis

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"time"
)

var ctx = context.Background()

func AcquireLock(rdb *redis.Client, key string, ttl time.Duration) (bool, string) {
	val := fmt.Sprintf("%d", time.Now().UnixNano())
	success, _ := rdb.SetNX(ctx, key, val, ttl).Result()
	return success, val
}

func ReleaseLock(rdb *redis.Client, key, val string) {
	lua := `
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end`
	rdb.Eval(ctx, lua, []string{key}, val)
}
